package com.xinlianshiye.im.service.impl;

import com.xinlianshiye.im.dao.UserGroupDao;
import com.xinlianshiye.im.bean.User;
import com.xinlianshiye.im.bean.UserGroup;
import com.xinlianshiye.im.service.UserGroupService;
import com.xinlianshiye.clouds.common.exception.WebMessageExceptionBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserGroupServiceImpl implements UserGroupService {

    public UserGroupServiceImpl(UserGroupDao userGroupDao, WebMessageExceptionBuilder exceptionBuilder) {
        this.userGroupDao = userGroupDao;
        this.exceptionBuilder = exceptionBuilder;
    }

    private final UserGroupDao userGroupDao;
    private final WebMessageExceptionBuilder exceptionBuilder;

    @Override
    public UserGroup getOrElseThrow(Integer id) {
        return userGroupDao.findById(id).orElseThrow(() -> exceptionBuilder.build(1, "记录不存在"));
    }

    @Override
    public UserGroup getOrCreateDefaultGroup(User user) {
        List<UserGroup> list = list(user.getId());
        if (list.size() == 0) {
            UserGroup group = new UserGroup();
            group.setName("我的好友");
            group.setUser(user);
            return userGroupDao.save(group);
        } else {
            return list.get(0);
        }
    }

    @Override
    public List<UserGroup> list(Integer userId) {
        return userGroupDao.findAllByUserId(userId);
    }
}
